package com.panda.utils;

import com.panda.annotation.SystemLog;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.TreeMap;

@Component
public class CosUtil {

    @Value("${ID}")
    private String ID;
    @Value("${KEY}")
    private String KEY;

    public RespondResult getCredential() {
        TreeMap<String, Object> config = new TreeMap<>();
        Response response;
        try {
            // 云 api 密钥 SecretId
            config.put("secretId", ID);
            // 云 api 密钥 SecretKey
            config.put("secretKey", KEY);

            // 设置域名
            // config.put("host", "sts.tencentcloudapi.com");

            // 临时密钥有效时长，单位是秒
            config.put("durationSeconds", 1800);

            // 换成你的 bucket
            config.put("bucket", "panda-1300922881");
            // 换成 bucket 所在地区
            config.put("region", "ap-guangzhou");

            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            config.put("allowPrefixes", new String[]{
                    "video/*", "image/*", "*"
            });

            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:PostObject",
                    // 删除
                    "name/cos:DeleteObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);
            response = CosStsClient.getCredential(config);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("no valid secret !");
        }
        return RespondResult.okResult(response);
    }
}
